
import { useEffect, useRef, useState } from 'react';
// import OSS from './aliyun-upload-sdk/lib/aliyun-oss-sdk-6.17.1.min'
// import './aliyun-upload-sdk/aliyun-upload-sdk-1.5.3.min'
import { uid } from '@/utils';
import { allGet } from '@/services/pc';
import { Progress } from 'antd';
import styles from './index.less';
import { spawn } from '@umijs/utils';
import request from '@/utils/request';
import axios from 'axios';
// window.OSS = OSS;



export type useAliyunUploadProps = {
  region: string;
  userId: string;
  timeout?: number;
  partSize?: number;
  parallel?: number;
  retryCount?: number;
  retryDuration?: number;
  onChange?: (fileList: any[], file: any,) => void;
  onSuccess?: (file: any,) => void;
  getAliyunAuth?: (params: { Title: string }) => any;
  refreshAliyunAuth?: (params: { VideoId: string }) => any;
}

export const useAliyunUpload = ({
  region,
  userId,
  getAliyunAuth,
  refreshAliyunAuth,
  timeout = 60000,
  partSize = 1048576,
  parallel = 5,
  retryCount = 3,
  retryDuration = 2,
  onChange,
  onSuccess,
}: useAliyunUploadProps) => {
  const AliyunUploaderRef = useRef<any>({})

  const handleChange = (uploadInfo) => {
    AliyunUploaderRef?.current?.onChange?.(AliyunUploaderRef.current?.listFiles()?.map(item => item.file), uploadInfo.file);
    onChange?.(AliyunUploaderRef.current?.listFiles()?.map(item => item.file), uploadInfo.file)
  }

  const handSuccess = (uploadInfo) => {
    onSuccess?.(uploadInfo.file)
  }
  const init = () => {
    const AliyunUpload = window?.AliyunUpload;

    if (!AliyunUpload || !getAliyunAuth || !refreshAliyunAuth) return;
    AliyunUploaderRef.current = new AliyunUpload.Vod({
      timeout,
      partSize: Math.round(partSize || 1048576),
      parallel,
      retryCount: retryCount || 3,
      retryDuration: retryDuration || 2,
      region: region,
      userId: userId,
      // 添加文件成功
      addFileSuccess: function (uploadInfo) {
        // self.uploadDisabled = false
        // self.resumeDisabled = false
        // self.statusText = '添加文件成功, 等待上传...'
        console.log("addFileSuccess: " + uploadInfo.file.name)
      },
      // 开始上传
      onUploadstarted: async (uploadInfo) => {
        // 如果是 UploadAuth 上传方式, 需要调用 uploader.setUploadAuthAndAddress 方法
        // 如果是 UploadAuth 上传方式, 需要根据 uploadInfo.videoId是否有值，调用点播的不同接口获取uploadauth和uploadAddress
        // 如果 uploadInfo.videoId 有值，调用刷新视频上传凭证接口，否则调用创建视频上传凭证接口
        // 注意: 这里是测试 demo 所以直接调用了获取 UploadAuth 的测试接口, 用户在使用时需要判断 uploadInfo.videoId 存在与否从而调用 openApi
        // 如果 uploadInfo.videoId 存在, 调用 刷新视频上传凭证接口(https://help.aliyun.com/document_detail/55408.html)
        // 如果 uploadInfo.videoId 不存在,调用 获取视频上传地址和凭证接口(https://help.aliyun.com/document_detail/55407.html)
        if (!uploadInfo.videoId) {
          // let createUrl = 'https://www.cgjoy.com/app.php?mod=video&do=aliyun&version=pc1.0&action=CreateUploadVideo&Title=123.mp4&CateId=1000422147'
          const data = await getAliyunAuth({ Title: uploadInfo.file.name });
          const { UploadAuth, UploadAddress, VideoId } = data;

          AliyunUploaderRef.current.setUploadAuthAndAddress(uploadInfo, UploadAuth, UploadAddress, VideoId)
          console.log(data, 111111)
        } else {
          // 如果videoId有值，根据videoId刷新上传凭证
          // https://help.aliyun.com/document_detail/55408.html?spm=a2c4g.11186623.6.630.BoYYcY
          // let refreshUrl = 'https://demo-vod.cn-shanghai.aliyuncs.com/voddemo/RefreshUploadVideo?BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&Title=haha1&FileName=xxx.mp4&VideoId=' + uploadInfo.videoId

          const data = await refreshAliyunAuth({ VideoId: uploadInfo.videoId })

          // let refreshUrl = 'https://demo-vod.cn-shanghai.aliyuncs.com/voddemo/RefreshUploadVideo?BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&Title=haha1&FileName=xxx.mp4&VideoId=' + uploadInfo.videoId        
          const { UploadAuth, UploadAddress, VideoId } = data;

          AliyunUploaderRef.current.setUploadAuthAndAddress(uploadInfo, UploadAuth, UploadAddress, VideoId)
        }
      },
      // 文件上传成功
      onUploadSucceed: function (uploadInfo) {
        uploadInfo.file.status = 'done';
        const { file, ...response } = uploadInfo
        uploadInfo.file.response = response;
        handleChange(uploadInfo);
        handSuccess(uploadInfo)
        // console.log("onUploadSucceed: " + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object)
        // self.statusText = '文件上传成功!'
      },
      // 文件上传失败
      onUploadFailed: function (uploadInfo, code, message) {

        uploadInfo.file.status = 'error';
        handleChange(uploadInfo);
        console.log("onUploadFailed: file:" + uploadInfo.file.name + ",code:" + code + ", message:" + message)
        // self.statusText = '文件上传失败!'
      },
      // 取消文件上传
      onUploadCanceled: function (uploadInfo, code, message) {
        uploadInfo.file.status = 'cancel';
        handleChange(uploadInfo);
        // console.log("Canceled file: " + uploadInfo.file.name + ", code: " + code + ", message:" + message)
        // self.statusText = '文件已暂停上传'
      },
      // 文件上传进度，单位：字节, 可以在这个函数中拿到上传进度并显示在页面上
      onUploadProgress: function (uploadInfo, totalSize, progress) {
        uploadInfo.file.status = 'uploading';
        uploadInfo.file.percent = Math.ceil(progress * 100);
        handleChange(uploadInfo);
        // console.log("onUploadProgress:file:" + uploadInfo.file.name + ", fileSize:" + totalSize + ", percent:" + Math.ceil(progress * 100) + "%")
        // let progressPercent = Math.ceil(progress * 100)
        // self.authProgress = progressPercent
        // self.statusText = '文件上传中...'
      },
      // 上传凭证超时
      onUploadTokenExpired: async (uploadInfo) => {
        // 上传大文件超时, 如果是上传方式一即根据 UploadAuth 上传时
        // 需要根据 uploadInfo.videoId 调用刷新视频上传凭证接口(https://help.aliyun.com/document_detail/55408.html)重新获取 UploadAuth
        // 然后调用 resumeUploadWithAuth 方法, 这里是测试接口, 所以我直接获取了 UploadAuth
        const data = await refreshAliyunAuth({ VideoId: uploadInfo.videoId })
        const { UploadAuth, } = data;
        AliyunUploaderRef.current.resumeUploadWithAuth(UploadAuth)
      },
      // 全部文件上传结束
      onUploadEnd: function (uploadInfo) {
        console.log("onUploadEnd: uploaded all the files")
        // self.statusText = '文件上传完毕'
      }
    })
  }
  useEffect(() => {
    init();
  }, []);
  return { AliyunUploaderRef, };
}

const getAliyunAuth = async (data = {}) => {
  // let createUrl = '/api2/voddemo/CreateUploadVideo?Title=testvod1&FileName=aa.mp4&BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&VideoId=5bfcc7864fc14b96972842172207c9e6'
  // const reponse = await request.get(createUrl)
  // return reponse;
  const response = await allGet({ params: { mod: 'video', do: 'aliyun', version: 'pc1.0', action: 'CreateUploadVideo', CateId: '1000422147', ...data, } })
  return response?.data || {}
}

const refreshAliyunAuth = async (data = {}) => {
  // let refreshUrl = '/api2/voddemo/RefreshUploadVideo?BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&Title=haha1&FileName=xxx.mp4&VideoId=' + data.VideoId

  // const reponse = await request.get(refreshUrl)
  // return reponse

  const response = await allGet({ params: { mod: 'video', do: 'aliyun', version: 'pc1.0', action: 'RefreshUploadVideo', ...data, } })
  return response?.data || {}
}

const Index = () => {

  const [fileList, setFlieList] = useState<any>([]);
  const onChange = (fileList, file) => {
    setFlieList(fileList)
  }
  const { AliyunUploaderRef } = useAliyunUpload({
    region: 'cn-shanghai',
    userId: '1303984639806000',
    onChange,
    getAliyunAuth,
    refreshAliyunAuth,
  });


  useEffect(() => {
    console.log(AliyunUploaderRef, 22222)
  }, [])

  const onSelectFile = (e) => {
    const files = e.target.files;
    const arr = [...fileList];
    var userData = '{"Vod":{}}'
    if (files.length > 0) {
      files.forEach(file => {
        file.uid = uid(15)
        AliyunUploaderRef.current.addFile(file, null, null, null, userData)
        arr.push(file);
      });
    }
    setFlieList(arr);
    AliyunUploaderRef.current.startUpload();
    (inputRef.current as any).value = ''
  }
  const handleStopFile = (file) => {
    const list = AliyunUploaderRef.current?.listFiles() || [];
    console.log(list,)

    const index = list.findIndex(item => item.file.uid === file.uid);
    if (index >= 0) {
      AliyunUploaderRef.current?.cancelFile(index)
    }
  }
  const handleResumeFile = (file) => {
    const list = AliyunUploaderRef.current?.listFiles() || [];
    console.log(list,)

    const index = list.findIndex(item => item.file.uid === file.uid);

    if (index >= 0) {
      const file = list[index].file;
      file.status = 'uploading';
      AliyunUploaderRef.current?.resumeFile(index)
      AliyunUploaderRef.current?.startUpload()
    }

  }
  const handleDeleteFile = (file) => {
    const list = AliyunUploaderRef.current?.listFiles() || [];
    console.log(list,)
    const index = list.findIndex(item => item.file.uid === file.uid);
    const stateIndex = fileList.findIndex(item => item.uid === file.uid);
    if (stateIndex >= 0) {
      const newFileList = [...fileList];
      newFileList.splice(stateIndex, 1);
      setFlieList(newFileList);
    }
    if (index >= 0) {
      AliyunUploaderRef.current?.stopUpload()
      AliyunUploaderRef.current?.cancelFile(index)
      AliyunUploaderRef.current?.deleteFile(index)
      AliyunUploaderRef.current?.startUpload()
    }

  }
  const inputRef = useRef<HTMLInputElement>(null);
  return <div style={{ background: '#fff', height: '100vh' }}>
    <div className={styles.uploadWrapper}>
      <input className={styles.input} ref={inputRef} type="file" onChange={onSelectFile} multiple />
    </div>

    {fileList.map(item => {
      return <div className={styles.progressWrapper} key={item.uid}>
        <div className={styles.text}>  {item.name}</div>

        <Progress percent={item.percent} />
        <div className={styles.handles}>
          {item.status === 'uploading' && <span onClick={() => handleStopFile(item)}>暂停</span>}
          {item.status === 'cancel' && <span onClick={() => handleResumeFile(item)}>继续</span>}
          <span onClick={() => handleDeleteFile(item)}>删除</span>
        </div>
      </div>
    }
    )}

  </div>
}


export default Index;